# -*- coding: utf-8 -*-
import sys
import logging
from lxml import etree
from xadmin.model import *
from xadmin.lib.base import *
from xadmin.lib.associations import Association

class CRPRAssociation(Association):
    def get(self):
        c.crprassociations = Session.query(CrPrAssociation).all()
        return render('/associations/crpr.mako')

    def getByProject(self, project):
        try:
            project = Session.query(Project).get(project)
            associations = Session.query(ClientRequirement).add_entity(CrPrAssociation).join('product_requirement_assoc').filter(ClientRequirement.project_id==project.id).all()
            c.crprassociations = []
            for association in associations:
                c.crprassociations.append(association[1])
            return render('/associations/crpr.mako')
        except:
            print "ERROR: ", sys.exc_info()[0]
            return ''

    def create(self, project, data):
        try:
            project = Session.query(Project).get(project)
            tree = etree.fromstring(data.encode())
            associations = tree.xpath('/associations/association')
            for association in associations:
                cr_id = association[0].xpath('id')[0].text
                pr_id = association[1].xpath('id')[0].text
                cr = Session.query(ClientRequirement).get(cr_id)
                pr = Session.query(ProductRequirement).get(pr_id)
                res = self._exists(cr_id, pr_id)
                if not res:
                    assoc = CrPrAssociation()
                    assoc.product_requirements = pr
                    cr.product_requirement_assoc.append(assoc)
                    Session.save(assoc)
                    Session.commit()
                else:
                    assoc = res
            return assoc
        except:
            print "ERROR: ", sys.exc_info()[0]
            return None

    def delete(self):
        pass

    def _exists(self, cr_id, pr_id):
        try:
            assoc = Session.query(CrPrAssociation).filter_by(cr_id=cr_id, pr_id=pr_id).one()
            print assoc
            return assoc
        except:
            return None